package com.dailyblue.example.springcloud.gateway.predicate;

import com.dailyblue.example.springcloud.gateway.bean.Age;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

@Component
@Slf4j
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<Age> {

    public AgeRoutePredicateFactory() {
        super(Age.class);
    }

    public List<String> shortcutFieldOrder() {
        return Arrays.asList("minAge", "maxAge");
    }

    @Override
    public Predicate<ServerWebExchange> apply(Age config) {
        int min = config.getMinAge();
        int max = config.getMaxAge();
        return exchange -> {
            ServerHttpRequest request = exchange.getRequest();
            MultiValueMap<String, String> queryParams = request.getQueryParams();
            String firstAge = queryParams.getFirst("age");
            // 获取到了请求参数age的值
            int age = Integer.parseInt(firstAge);
            // 如果是true代表通过，否则条件失败
            return age >= min && age <= max;
        };
    }
}
